package util

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"gitee.com/worklz/grpc-mtls-demo/server-order/config"
	"google.golang.org/grpc/credentials"
	"os"
	"path/filepath"
	"runtime"
)

// LoadServerMTLSCredentials 加载当前服务需要验证来访调用客户端的mTLS凭证
func LoadServerMTLSCredentials() (credentials.TransportCredentials, error) {
	// 获取项目根目录绝对路径
	_, filename, _, _ := runtime.Caller(0)
	projectRoot := filepath.Dir(filepath.Dir(filename)) // 根据实际项目结构调整层级
	demoRootPath := filepath.Join(projectRoot, "..", "..")

	// 拼接CA根证书路径
	caPath := filepath.Join(demoRootPath, "cert", "ca.pem")
	// 加载CA根证书（用于验证客户端证书）
	caCert, err := os.ReadFile(caPath)
	if err != nil {
		return nil, err
	}

	caPool := x509.NewCertPool()
	if !caPool.AppendCertsFromPEM(caCert) {
		return nil, err
	}

	// 拼接服务证书和私钥路径
	certPath := filepath.Join(demoRootPath, config.ServerName, "cert", fmt.Sprintf("%s.pem", config.ServerName))
	keyPath := filepath.Join(demoRootPath, config.ServerName, "cert", fmt.Sprintf("%s-key.pem", config.ServerName))

	// 加载服务证书和私钥
	cert, err := tls.LoadX509KeyPair(certPath, keyPath)
	if err != nil {
		return nil, err
	}

	// 配置TLS，要求并验证客户端证书
	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
		ClientAuth:   tls.RequireAndVerifyClientCert,
		ClientCAs:    caPool,
	}

	return credentials.NewTLS(tlsConfig), nil
}
